// 统一管理后端API请求
import axios from 'axios';

// 创建 axios 实例
const axiosInstance = axios.create({
    baseURL: '/api', // 替换为您的 API URL
});

// 添加请求拦截器以附加 token
axiosInstance.interceptors.request.use(config => {
    const token = localStorage.getItem('authToken');
    if (token) {
        config.headers['token'] = `Bearer ${token}`;
    }
    return config;
}, error => {
    console.error('Request Interceptor Error:', error);
    return Promise.reject(error);
});


// 登录
export const login = async (credentials) => {
    try {
        const response = await axiosInstance.post('/admin/login', credentials);
        return response.data;
    } catch (err) {
        console.log('登录失败', err);
        throw err;
    }
};

// 登出
export const logout = () => {
    return axiosInstance.post('/admin/logout')
        .then(res => res.data);
};

// 获取用户信息
export const getInfo = () => {
    return axiosInstance.get('/admin/getInfo')
        .then(res => res.data)
        .catch(err => {
            console.error("获取用户失败", err);
            throw err;
        });
};

// 更新用户信息
export const updateUserInfo = (userInfo) => {
    return axiosInstance.put('/admin/updateUserInfo', userInfo)
        .then(res => res.data)
        .catch(err => {
            console.error("更新用户信息失败", err);
            throw err;
        });
};

// 上传头像
export const uploadAvatar = (file) => {
    return axiosInstance.post('/admin/common/upload', file)
        .then(res => res.data)
        .catch(err => {
            console.error("上传头像失败", err);
            throw err;
        });
};

// 获取仪表盘数据
export const fetchDashboardData = () => {
    return axiosInstance.get('/admin/dashboard/data').then(res => res.data);
};

// 获取订单列表
export const fetchOrders = () => {
    return axiosInstance.get('/admin/orders').then(res => res.data).catch(err => {
        console.error("获取订单失败", err);
        throw err;
    });
};

// 删除订单
export const deleteOrder = (orderId) => {
    return axiosInstance.delete(`/admin/orders/${orderId}`).then(res => res.data).catch(err => {
        console.error("删除订单失败", err);
        throw err;
    });
};

// 导出订单报表
export const exportOrders = () => {
    return axiosInstance.post('/admin/orders/export', {}, {responseType: 'blob'}).then(res => res.data).catch(err => {
        console.error("导出订单失败", err);
        throw err;
    });
};

// 获取快递柜列表
export const fetchLockers = () => {
    return axiosInstance.get('/admin/lockers').then(res => res.data);
};

// 删除快递柜
export const deleteLocker = (lockerId) => {
    return axiosInstance.delete(`/admin/lockers/${lockerId}`).then(res => res.data);
};

// 获取角色列表
export const fetchRoles = async () => {
    try {
        const response = await axiosInstance.get('/admin/roles');
        return response.data;
    } catch (err) {
        console.log('获取角色失败', err);
        throw err;
    }
};

// 删除角色
export const deleteRole = async (roleId) => {
    try {
        const response = await axiosInstance.delete(`/admin/roles/${roleId}`);
        return response.data;
    } catch (err) {
        console.log('删除角色失败', err);
        throw err;
    }
};

// 添加角色
export const addRole = async (roleData) => {
    try {
        const response = await axiosInstance.post('/admin/roles', roleData);
        return response.data;
    } catch (err) {
        console.log('添加角色失败', err);
        throw err;
    }
};

// 更新角色
export const updateRole = async (roleData) => {
    try {
        const response = await axiosInstance.put(`/admin/roles/${roleData.id}`, roleData);
        return response.data;
    } catch (err) {
        console.log('更新角色失败', err);
        throw err;
    }
};

// 获取系统状态
export const fetchSystemStatus = async () => {
    try {
        const response = await axiosInstance.get('/admin/system/status');
        return response.data;
    } catch (err) {
        console.log('获取系统状态失败', err);
        throw err;
    }
};

// 添加快递柜
export const addLocker = (lockerData) => {
    return axiosInstance.post('/admin/lockers', lockerData).then(res => res.data);
};

// 更新快递柜
export const updateLocker = (lockerData) => {
    return axiosInstance.put(`/admin/lockers/${lockerData.id}`, lockerData).then(res => res.data);
};

// 获取仪表盘统计数据
export const fetchDashboardStats = () => {
    return axiosInstance.get('/admin/dashboard/stats')
        .then(res => res.data)
        .catch(err => {
            console.error("获取仪表盘统计数据失败", err);
            throw err;
        });
};

export function getOrders() {
    return new Promise((resolve, reject) => {
        // 模拟 API 调用
        setTimeout(() => {
            resolve(data); // 或者 reject(error);
        }, 1000);
    });
}

const api = {
    login,
    logout,
    getInfo,
    updateUserInfo,
    uploadAvatar,
    fetchDashboardData,
    fetchOrders,
    deleteOrder,
    fetchLockers,
    deleteLocker,
    fetchRoles,
    deleteRole,
    addRole,
    updateRole,
    fetchSystemStatus,
    addLocker,
    updateLocker,
    fetchDashboardStats,
    getOrders,
};

export default api;